<template>
	<view class="page">

		<view class="top-vie">
			<view class="top-blad" @click="goBack" :style="{display:topshow==true?'block':'none'}">
				<u-icon top="3" name="arrow-left" color="#ffffff" size="26"></u-icon>
			</view>
		</view>
		<u-swiper radius="0" class="wine-image" imgMode="scaleToFill" bgColor="#ffffff" :height="330"
			:list="wine.imageUrl"></u-swiper>
		<!-- 酒的详情信息 -->
		<view class="wine-details">
			<!-- 根据你的数据结构展示相关信息，以下为示例 -->
			<view class="wine-info">
				<view style="display: flex;justify-content: space-between;">
					<text class="wine-name">{{ wine.wname }}</text>
					<text class="wine-price">${{ parseFloat(wine.price).toFixed(2) }}</text>
				</view>
				<view class="wine-origin">产地:<text class="line-color">{{ wine.origin }}</text><text
						style="margin-left: 1rem;">类型:<text class="line-color">{{ wine.type }}</text></text></view>
				<text class="wine-year">生成年份:<text class="line-color">{{ wine.vintageYear }}</text></text>
				<view class="wine-alcohol">酒精含量:<text class="line-color">{{ wine.alcoholContent }}%</text><text
						style="margin-left: 1rem;" class="wine-volume">毫升:<text
							class="line-color">{{ wine.volumeMl }}ml</text></text></view>
				<view class="wine-stock">库存:<text class="line-color"> {{ wine.stockQuantity }}</text></view>
				<view class="wine-description">{{ wine.description }}</view>
			</view>
		</view>

		<!-- 预约按钮 -->
		<button :style="{background: isexist ? '#968f8d' : ''}" class="reserve-button" @tap="handleClick('handleReservation')">{{isexist==false?"预约":"已预约"}}</button>
		<u-popup ref="modal" :customStyle="{'width':'18rem','padding':'1rem'}" :show="isModalVisible" round="10"
			mode="center" @close="closeModal">
			<view class="box-title fc">
				<i></i>
				<text style="font-size: 0.7rem;">预约确认</text>
				<view style="flex: 1;">

				</view>
				<image style="width: 0.6rem; 
    height: 0.6rem;" @tap="closeModal()" src="@/static/tabBar/xx.png" mode="widthFix"></image>
			</view>
			<u-divider></u-divider>

			<view class="">
				<view class="input-row fc-bet">
					<view class="left" style="font-size: 0.6rem;">
						数量
					</view>
					<view class="right fc">
						<u-number-box :step="1" v-model="num" @minus="decreaseAmount"
							@plus="increaseAmount"></u-number-box>
					</view>
				</view>

			</view>
			<u-divider></u-divider>
			<view class="pay-style-selects" style="border-bottom: 1px solid rgba(83, 123, 155, 0.1);">
				<view class="pay-select-item c_xzczfs checked" data-id="1" name="c_zffs" @click="selectPayment(1)">
					<view class="img">
						<image style="width: 100%;height: 100%;" src="@/static/tabBar/icon_ktye.png" alt="">
						</image>
					</view>
					<view class="name">
						<text style="flex: 1;">支付金额( <text class="red"
								style="font-weight: 600;">{{parseFloat(wine.price*num).toFixed(2) }}</text> )</text>
						<image style="width:1rem;height: 100%;" src="@/static/tabBar/yueb-ok.png" mode="widthFix">
						</image>
					</view>
				</view>
			</view>
			<u-divider></u-divider>
			<view class="zifu">
				<u-button style="width: 46%;" type="error" @click="pendingPayment"
					:disabled="wine.price*num <= 0">等下支付</u-button>
				<u-button style="width: 46%;" type="success" @click="confirmInvestment"
					:disabled="wine.price*num <= 0">确认支付</u-button>
			</view>
		</u-popup>
		<u-popup :show="ispaypass" mode="center">
			<view style="margin: 1rem;z-index: 30000;">
				<u-code-input :dot="true" :disabled-keyboard="true" v-model="paymentPassword" @change="passwordinput"
					:maxlength="6"></u-code-input>
			</view>

		</u-popup>
		<u-keyboard :focus="true" :tooltip="true" :showTips="false" :random="true" :dotDisabled="true"
			@change="keyboard" @backspace="onBackspace" @cancel="cancel" ref="uKeyboard" mode="number"
			:show="iskeyboard"></u-keyboard>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 根据你的数据结构提供相应的酒的信息
				wine: {
					imageUrls: ["http://img06.jiuxian.com/2024/0111/17a8113edc3c46cf91261b1c29e574135.jpg",
						"http://img07.jiuxian.com/2023/0306/a25382574f4c4cf580665e83cae98fb15.jpg",
						"http://img07.jiuxian.com/2023/0307/458562f48b39400ea4d453a88bfd3aea5.jpg"
					],

				},
				isexist: false,
				rechargeCoins: 0,
				num: 1,
				wineId: 0,
				userId: 0,
				scrollPosition: 0,
				topshow: true,
				isModalVisible: false,
				ispaypass: false,
				iskeyboard: false,
				paymentPassword: ""
			};
		},
		onLoad(val) {
			this.wineId = Number(val.wineId)
			this.userId = this.$store.state.uid
		},
		computed: {
			userInfo() {
				return this.$store.getters.userInfo;
			},
			// 	containerStyle() {
			// 		// 根据滚动位置动态计算背景色的透明度

			// 		return {
			// 			backgroundColor: `rgba(255, 255,255, ${this.scrollPosition})`, // 使用 rgba 表示颜色，最后一位是透明度
			// 		};
			// 	},
		},
		onPageScroll(e) {
			let topRate = e.scrollTop / 100;
			// if (topRate > 1) {
			// 	topRate = 1;
			// }
			this.scrollPosition = topRate;
			if (topRate >= 0.7) {
				this.topshow = false
			} else {
				this.topshow = true
			}
			console.log(this.scrollPosition);
		},
		mounted() {
			this.loadData()
			this.isExit()
		},
		methods: {
			cancel() {
				this.ispaypass = false;
				this.iskeyboard = false;
				this.isModalVisible = true;
				this.paymentPassword = ""
			},
			checkToken() {
				// 从 Vuex 中获取用户信息
				const token = uni.getStorageSync('token')
			
				// 检查用户信息中是否包含 token
				if (!token || !this.userId || !this.userInfo) {
					// 如果 token 不存在或为空，则显示登录提示
					this.$store.state.userInfo = null
					uni.removeStorageSync('userInfo')
					uni.showModal({
						title: '提示',
						content: '请登录后再进行操作',
						confirmText: '去登录',
						success: (res) => {
							if (res.confirm) {
								// 用户点击了确认按钮，跳转至登录页面
								this.goToLogin();
							}
						},
					});
					return false;
				}
				return true;

			},
			// 用户点击某个控件事件处理
			goToLogin() {
				uni.navigateTo({
					url: '/pages/login/index', // 前往登录页的路径，请根据实际情况修改
				});
			},
			handleClick(action, wineId, promotionId) {

				// // 检查用户是否已登录
				if (!this.checkToken()) {
					// 如果用户未登录，则不执行后续操作
					return;
				}

				// // 如果已登录，则根据不同的操作执行相应的操作
				switch (action) {
					case 'handleReservation':
						this.handleReservation();
						break;
					default:
						break;
				}
			},
			async pendingPayment() {
				const param = {
					wineId: this.wineId,
					userId: this.userId,
					quantity: this.num
				}
				const res = await this.$request.post('/system/wine-reservation/createPay', param)
				console.log(res);
				if (res.code === 200) {

					this.isModalVisible = false
				} else {
					this.$refs.uToast.show({
						type: 'error',
						title: '失败主题',
						message: res.message,
						iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
					});
				}
			},
			async loadData() {
				const param = {
					wineId: this.wineId
				}
				const res = await this.$request.get('/system/wine/WineByKey', param)
				console.log(res);
				if (res.code == 200) {
					this.wine = {
						...res.data.w,
						imageUrl: res.data.w.imageUrl.split(',')
					};
				}
			},
			async isExit() {
				const param = {
					wineId: this.wineId,
					userId: this.userId
				}
				const res = await this.$request.get('/system/wine-reservation/getExist', param)
				if (res.code == 200) {
					this.isexist = res.data.result
				}
			},
			// 处理预约按钮点击事件
			handleReservation() {
				// this.isModalVisible = true
				if (this.isexist==false) {
					uni.navigateTo({
						url: `/pages/tabBar/yuyue/details/result/result?wineId=${this.wineId}`
					})
				}
			},
			closeModal() {
				this.isModalVisible = false
			},
			decreaseAmount() {
				if (this.num > 0) {
					this.num--;
				}
			},
			increaseAmount() {
				this.num++;
			},
			onBackspace() {
				if (this.paymentPassword.length) {
					this.paymentPassword = this.paymentPassword.substr(0, this.paymentPassword.length - 1);
				}

				console.log("Payment password after backspace:", this.paymentPassword);
			},
			passwordinput(e) {
				this.paymentPassword += e
			},
			confirmInvestment() {
				this.ispaypass = true;
				this.iskeyboard = true;
				this.isModalVisible = false;
			},
			keyboard(e) {
				console.log(e);
				if (this.paymentPassword.length < 6) {
					this.paymentPassword += e;
					// this.$refs.uKeyboard.backspace()
				}
				if (this.paymentPassword.length >= 6) {
					this.finish()
					//封装的结束函数，后续还有请求接口和判断
				}

			},
			finish() {
				this.ispaypass = false;
				this.iskeyboard = false;
				this.payment()

				this.paymentPassword = ""

			},
			payment() {
				this.$refs.uToast.show({
					type: 'loading',
					title: '支付中...',
					message: "支付中...",
					iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/loading.png'
				})
				const param = {
					wineId: this.wineId,
					price: this.wine.price * this.num,
					userId: this.userId,
					quantity: this.num,
					paymentPassword: this.paymentPassword
				}
				this.$request.post('/system/wine-reservation/invest', JSON.stringify(param))
					.then(res => {
						if (res.code === 200) {
							this.$refs.uToast.show({
								type: 'success',
								title: '成功主题(带图标)',
								message: res.message,
							})
						} else {
							this.$refs.uToast.show({
								type: 'error',
								title: '失败主题',
								message: res.message,
								iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
							});
						}
					})
					.catch(error => {})
			},
			goBack() {
				uni.navigateBack()
			}
		},
	};
</script>

<style lang="scss" scoped>
	/* 根据需要添加样式 */
	// _wine-details.scss
	.top-vie {
		width: 100%;
		position: fixed;
		z-index: 1000;

		.top-blad {
			width: 2rem;
			height: 2rem;
			background-color: #676767;
			border-radius: 50%;
			display: flex;
			margin-top: 0.3rem;
			align-items: center;
			margin-left: 0.3rem;

		}
	}

	.wine-details {
		padding: 20px;
		border: 1px solid #f5f5f5;
		border-radius: 9px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		background-color: #fff;
		margin: 10px;
	}

	/deep/.u-keyboard {
		padding: 0px 0px 0px 0px;
	}

	// _wine-image.scss

	.wine-image {
		max-width: 100%;
		width: 100%;
		border-radius: 0;
		background-color: #fff;
	}

	// _wine-info.scss

	.wine-info {
		margin-top: 10px;
		font-size: 16px;
		color: #333;
	}


	.wine-name {
		font-size: 1.4rem;
		font-weight: bold;
		color: #000;
	}

	/deep/.u-modal__content {
		padding: 12px 25px 25px 25px;
		display: block;
		flex-direction: row;
		justify-content: center;
	}

	// _wine-origin.scss

	.wine-origin,
	.wine-type,
	.wine-year,
	.wine-alcohol,
	.wine-volume,
	.wine-stock,
	.wine-description {
		margin-bottom: 4px;
		margin-top: 5px;
		color: #666;

		.line-color {
			color: #000;
			font-weight: 400;
		}
	}

	.wine-price {
		font-size: 1.4rem;
		font-weight: bold;
		color: #f7061e;
	}

	.wine-description {
		color: #666;
	}

	// _reserve-button.scss

	.reserve-button {
		// padding: 10px 20px;
		font-size: 18px;
		width: 40%;
		margin: 0 auto;
		margin-top: 3rem;
		margin-bottom: 1rem;
		font-weight: bold;
		background-color: #ff4500;
		/* 背景颜色，这里使用了橙红色 */
		color: #fff;
		border: none;
		border-radius: 8px;
		cursor: pointer;
		transition: background-color 0.3s ease;
		/* 添加过渡效果 */
		text-align: center;

	}

	.box-title {
		width: 100%;
		display: flex;
		justify-content: space-between;

		i {
			width: 0.24rem;
			height: 0.6rem;
		}
	}

	.name {
		display: flex;
		justify-content: space-between;
	}

	.input-row {
		display: flex;
		justify-content: space-between;
	}

	.zifu {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>